#include "backoff.h"
#include "ui_backoff.h"


Backoff::Backoff(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Backoff)
{
    ui->setupUi(this);

    /****************摄像头******************/
    t_video = new QTimer(this);

    //初始化摄像头设备
    linux_v4l2_yuyv_init("/dev/video7");
    //开启摄像头的捕捉画面功能
    linux_v4l2_start_yuyv_capturing();

    connect(t_video,SIGNAL(timeout()),this,SLOT(video()));

    t_video->start(10);

    /*****************超声波探距****************/
    t_sr04 = new QTimer(this);

    //超声波sr04
    sr04_fd = ::open("/dev/gec6818_sr04",O_RDWR);
    if(sr04_fd < 0)
        perror("open /dev/gec6818_sr04:");

    connect(t_sr04,SIGNAL(timeout()),this,SLOT(get_distance()));

    t_sr04->start(500);

    /*****************************************/
    t_return = new QTimer(this);

    //key
    key_fd = ::open("/dev/my_key",O_RDWR);
    if(sr04_fd < 0)
        perror("open /dev/my_key:");

    connect(t_return,SIGNAL(timeout()),this,SLOT(go_home()));

    t_return->start(1000);

    /*****************************************/
    //子函数调用析构函数
    setAttribute(Qt::WA_DeleteOnClose);
}

Backoff::~Backoff()
{
    qDebug()<<"~Backoff"<<endl;

    t_sr04->stop();

    delete t_sr04;

    t_return->stop();

    delete t_return;

    ::close(sr04_fd);

    ::close(key_fd);

    delete ui;
}

void Backoff::video()
{
    //显示视频流
    //抓取一针图像
    bzero(&jpg_buf,sizeof(jpg_buf));
    linux_v4l2_get_yuyv_data(&jpg_buf);

    QPixmap map;

    map.loadFromData(jpg_buf.jpg_data,static_cast<unsigned int>(jpg_buf.jpg_size));

    ui->BackoffVideo->setPixmap(map);
}

void Backoff::get_distance()
{
    //获取当前车距
    int d = 0;
    double d1 = 0.0;
    int rt = ioctl(sr04_fd, GEC6818_SR04_DISTANCE, &d);     //获取超声波数据

    if(rt == 0)
    {
        if(d<20 || d>4000);
        else{
            d1 = d;
            d1 = d1/1000;
            QString msg = QString("%1 M").arg(d1);
            //qDebug()<<msg<<endl;
            ui->distance->setText(msg);

            if( (1450 <= d) && (d <= 1550))
                system("mplayer -af volume=20 ./prompt/1.5.m4a &");
            else if( (950 <= d) && (d <= 1050))
                system("mplayer -af volume=20 ./prompt/1.0.m4a &");
            else if( (480 <= d) && (d <= 520))
                system("mplayer -af volume=20 ./prompt/0.5.m4a &");
            else if(d < 300)
            {
                system("mplayer -af volume=20 ./prompt/stop.m4a &");
                QMessageBox::warning(this,"警告","停车！停车！",QMessageBox::Yes);
            }
        }
    }
}

void Backoff::go_home()
{
    int val = -1;
    //读取按键的状态
    int rt = ioctl(key_fd, GEC6818_K3_STA, &val);

    if(rt == 0)
    {
       if(val == 1)
       {
           qDebug()<<"K3 enter"<<endl;

           this->close();

           this->parentWidget()->show();
       }
    }
}

void Backoff::closeEvent(QCloseEvent *)
{
    qDebug()<<"Backoff close"<<endl;

    t_video->stop();

    delete t_video;

    //退出摄像头
    linux_v4l2_yuyv_quit();
}
